<template>
  <div
    v-if="visible && suggestions.length > 0"
    class="autocomplete-dropdown"
    :style="dropdownStyle"
  >
    <div class="autocomplete-header">
      <span class="suggestion-count">{{ suggestions.length }} 个建议</span>
      <span class="shortcut-hint">↑↓ 选择 • Enter 确认 • Esc 关闭</span>
    </div>
    
    <div class="suggestions-list">
      <div
        v-for="(suggestion, index) in suggestions"
        :key="`${suggestion.type}-${suggestion.value}-${index}`"
        class="suggestion-item"
        :class="{ 
          active: index === activeIndex,
          [`suggestion-${suggestion.type}`]: true 
        }"
        @click="selectSuggestion(suggestion)"
        @mouseenter="activeIndex = index"
      >
        <div class="suggestion-main">
          <el-icon class="suggestion-icon">
            <component :is="getSuggestionIcon(suggestion.type)" />
          </el-icon>
          <span class="suggestion-label">{{ suggestion.label }}</span>
          <span class="suggestion-type-badge">{{ suggestion.type }}</span>
        </div>
        
        <div v-if="suggestion.description" class="suggestion-description">
          {{ suggestion.description }}
        </div>
        
        <!-- 变量类型的额外信息 -->
        <div v-if="suggestion.type === 'variable' && suggestion.meta" class="suggestion-meta">
          <span class="meta-type">类型: {{ suggestion.meta.type }}</span>
          <span v-if="suggestion.meta.example" class="meta-example">
            示例: {{ suggestion.meta.example }}
          </span>
        </div>
      </div>
    </div>
    
    <!-- 没有匹配项时的提示 -->
    <div v-if="suggestions.length === 0 && searchTerm" class="no-suggestions">
      <el-icon><Search /></el-icon>
      <span>没有找到匹配的建议</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import { 
  User, 
  Document, 
  Operation, 
  Search,
  Tools
} from '@element-plus/icons-vue'
import type { Suggestion } from './type'

interface Props {
  visible: boolean
  suggestions: Suggestion[]
  activeIndex: number
  position: { x: number; y: number }
  searchTerm?: string
}

interface Emits {
  (e: 'select', suggestion: Suggestion): void
  (e: 'update:activeIndex', index: number): void
  (e: 'close'): void
  (e: 'navigation', direction: 'up' | 'down'): void
  (e: 'confirm'): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  suggestions: () => [],
  activeIndex: 0,
  searchTerm: ''
})

const emit = defineEmits<Emits>()

// 响应式数据
const activeIndex = ref(props.activeIndex)

// 计算属性
const dropdownStyle = computed(() => ({
  position: 'fixed',
  left: `${props.position.x}px`,
  top: `${props.position.y}px`,
  zIndex: 2000
}))

// 监听器
watch(() => props.activeIndex, (newIndex) => {
  activeIndex.value = newIndex
})

watch(activeIndex, (newIndex) => {
  emit('update:activeIndex', newIndex)
})

// 方法
const selectSuggestion = (suggestion: Suggestion) => {
  // 验证建议数据的完整性
  if (!suggestion || !suggestion.value) {
    console.warn('AutoComplete: 无效的建议数据', suggestion)
    return
  }
  
  // 确保建议包含必要的字段
  const validatedSuggestion: Suggestion = {
    label: suggestion.label || suggestion.value,
    value: suggestion.value,
    type: suggestion.type || 'variable',
    description: suggestion.description,
    meta: suggestion.meta
  }
  
  emit('select', validatedSuggestion)
}

const getSuggestionIcon = (type: string) => {
  switch (type) {
    case 'variable':
      return User
    case 'function':
      return Tools
    case 'operator':
      return Operation
    default:
      return Document
  }
}

// 键盘导航
const handleKeydown = (event: KeyboardEvent) => {
  if (!props.visible) return
  
  switch (event.key) {
    case 'ArrowDown':
      event.preventDefault()
      const nextIndex = Math.min(activeIndex.value + 1, props.suggestions.length - 1)
      activeIndex.value = nextIndex
      emit('navigation', 'down')
      scrollToActiveItem()
      break
    case 'ArrowUp':
      event.preventDefault()
      const prevIndex = Math.max(activeIndex.value - 1, 0)
      activeIndex.value = prevIndex
      emit('navigation', 'up')
      scrollToActiveItem()
      break
    case 'Enter':
      event.preventDefault()
      if (props.suggestions[activeIndex.value]) {
        emit('confirm')
        selectSuggestion(props.suggestions[activeIndex.value])
      }
      break
    case 'Escape':
      event.preventDefault()
      emit('close')
      break
    case 'Tab':
      // Tab键也可以确认选择
      event.preventDefault()
      if (props.suggestions[activeIndex.value]) {
        emit('confirm')
        selectSuggestion(props.suggestions[activeIndex.value])
      }
      break
  }
}

const scrollToActiveItem = () => {
  nextTick(() => {
    const activeElement = document.querySelector('.suggestion-item.active')
    if (activeElement) {
      activeElement.scrollIntoView({ block: 'nearest' })
    }
  })
}

// 暴露方法给父组件
defineExpose({
  handleKeydown
})
</script>

<style scoped>
.autocomplete-dropdown {
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  min-width: 280px;
  max-width: 400px;
  max-height: 300px;
  overflow: hidden;
  font-size: 14px;
}

.autocomplete-header {
  padding: 8px 12px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.suggestion-count {
  font-size: 12px;
  color: #606266;
  font-weight: 500;
}

.shortcut-hint {
  font-size: 11px;
  color: #909399;
}

.suggestions-list {
  max-height: 240px;
  overflow-y: auto;
}

.suggestion-item {
  padding: 10px 12px;
  cursor: pointer;
  border-bottom: 1px solid #f5f7fa;
  transition: all 0.2s ease;
  position: relative;
}

.suggestion-item:hover,
.suggestion-item.active {
  background-color: #f0f9ff;
}

.suggestion-item.active {
  border-left: 3px solid #409eff;
}

.suggestion-item:last-child {
  border-bottom: none;
}

.suggestion-main {
  display: flex;
  align-items: center;
  gap: 8px;
}

.suggestion-icon {
  font-size: 16px;
  color: #909399;
}

.suggestion-variable .suggestion-icon {
  color: #67c23a;
}

.suggestion-function .suggestion-icon {
  color: #e6a23c;
}

.suggestion-operator .suggestion-icon {
  color: #f56c6c;
}

.suggestion-label {
  font-weight: 500;
  color: #303133;
  flex: 1;
}

.suggestion-type-badge {
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 3px;
  font-weight: 500;
  text-transform: uppercase;
}

.suggestion-variable .suggestion-type-badge {
  background-color: #f0f9ff;
  color: #409eff;
}

.suggestion-function .suggestion-type-badge {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.suggestion-operator .suggestion-type-badge {
  background-color: #fef0f0;
  color: #f56c6c;
}

.suggestion-description {
  font-size: 12px;
  color: #606266;
  margin-top: 4px;
  line-height: 1.4;
}

.suggestion-meta {
  margin-top: 6px;
  display: flex;
  gap: 12px;
  font-size: 11px;
}

.meta-type {
  color: #909399;
}

.meta-example {
  color: #67c23a;
  font-family: 'Courier New', monospace;
}

.no-suggestions {
  padding: 20px;
  text-align: center;
  color: #909399;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.no-suggestions .el-icon {
  font-size: 24px;
  opacity: 0.5;
}

/* 滚动条样式 */
.suggestions-list::-webkit-scrollbar {
  width: 6px;
}

.suggestions-list::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.suggestions-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.suggestions-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>